import React from 'react';
import {
    Button,
    Text,
    View,
    Image,
    StyleSheet,
    Dimensions,
    StatusBar,
    ActivityIndicator,
    FlatList,
    ScrollView,
    RefreshControl,
    Animated,
    TouchableHighlight,
    TextInput,
    TouchableOpacity, DeviceEventEmitter, Modal, Keyboard
} from 'react-native';
import Swiper from 'react-native-swiper';
import { MarqueeHorizontal, MarqueeVertical } from 'react-native-marquee-ab';
import Styles from './ListStyles';
const { width, height } = Dimensions.get('window')

import app from '../../../../app.json';
import Ugame from '../../../../Ugame';
import Httpc from "../../../utils/Httpc";
import Utils from "../../../utils/Utils";
import REQUEST from "../../../../REQUEST";

import DLTBall from "./DLTBall";

var BETTYPE = {
    One: 0,
    Multiple: 1,
    Bladder: 2
}


export default class DLTBetList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loaded: false,
            refreshing: false,
            toastModelVisible: false,
            message: '',
            isGold: 0,//0不是大神1是大神
            opt_status: false,

            Number: null,//当前期号

            bet_count: 0,//数量
            bet_amount: 0,//投注金额

            name: '大乐透',
            isPhoto: 1,//是否需要上传图片
            Mult: 1,//倍数
            IsAdd: 0,//是否追加 0不追加1追加
            IncNum: 1,//追加多少期
            IsFollow: 0,//是否跟单           
            Title: "大乐透",
            Commis: 0,
            IsShow: 0,
            Metro: "",
            betNumber: [],
            betRecords: [],

            computeState: true,
        };
        this.keyboardDidHideListener = null;
        this._time = null;
    }
    static navigationOptions = {
        title: '确认投注',
        //header: null,  //隐藏顶部导航栏
        //tabBarVisible: false, // 隐藏底部导航栏
        headerStyle: {
            backgroundColor: '#d0162e',
            paddingTop: 8
        },
        headerTintColor: '#fff',
        headerTitleStyle: {
            //fontWeight: 'bold',
        },
    }
    componentWillMount() {
        //监听键盘隐藏事件
        this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide',
            this.keyboardDidHideHandler.bind(this));
    }

    componentWillUnmount() {
        //卸载键盘隐藏事件监听
        if (this.keyboardDidHideListener != null) {
            this.keyboardDidHideListener.remove();
        }
        this.setState({
            Number: null,//当前期号
            bet_count: 0,//数量
            bet_amount: 0,//投注金额
            betNumber: [],
            betRecords: [],
        });

    }
    //键盘隐藏事件响应
    keyboardDidHideHandler(event) {
        let beishuInput = this.state.beishuInput;
        if (beishuInput == '' || beishuInput < 1) {
            beishuInput = 1;
            this.setState({
                beishuInput: parseInt(beishuInput).toString()
            })
        }
    }
    componentDidMount() {
        const { navigation } = this.props;
        let Number = navigation.getParam("Number");
        this.getIsGold();
        this.setState({
            Number: Number,
            BetNumber: Ugame.DLTSelectList
        }, () => {
            this.computeBetNumber();
        })
    }
    getIsGold = () => {
        Httpc.get(REQUEST.GetUserInfo, { token: Ugame.info.Token }, (res) => {
            if (res.StatusCode == 1) {
                this.setState({
                    isGold: res.Data.isGold
                })
            }
        })
    }
    computeBetNumber() {
        let { BetNumber, Mult, IncNum, IsAdd } = this.state;
        let bet_count = 0;
        for (let i = 0; i < BetNumber.length; i++) {
            bet_count += BetNumber[i].betRecords.length;
        }
        let bet_amount = (bet_count * app.PRICE * Mult * (IncNum == '' ? 1 : IncNum)) * (IsAdd == 0 ? 1 : 1.5);
        this.setState({
            bet_count: bet_count,
            bet_amount: bet_amount
        });
    }
    _add_bet = () => {
        DeviceEventEmitter.emit('update_betNumber', {});
        this.props.navigation.navigate('DLTGame');
    }
    _clear_bet = () => {
        this.setState({
            BetNumber: Ugame.clearDLTSelectList()
        });
    }
    on_show_bet = (index) => {
        DeviceEventEmitter.emit('update_betNumber', { selected_id: index });
        this.props.navigation.navigate('DLTGame');
    }
    do_bet_order = () => {
        let { computeState, name, isPhoto, Mult, IsAdd, IncNum, IsFollow, Title, Commis, IsShow, Metro, BetNumber } = this.state;
        if (computeState == false) {
            return;
        }
        if (BetNumber.length == 0) {
            this.do_toast('请至少选择一注', 1000);
            return;
        }
        let betNs = [];
        let berRs = [];
        for (let i = 0; i < BetNumber.length; i++) {
            let betN = BetNumber[i].BetNumber;
            let berR = BetNumber[i].betRecords;
            let NoID = ((i + 1) * 10) + betN.Type;
            betN.NoID = NoID;
            for (let j = 0; j < berR.length; j++) {
                berR[j].NoID = NoID;
                berR[j].multNum = Mult;
                berRs.push(berR[j]);
            }
            betNs.push(betN);
        }
        let postBetData = {
            name: name,
            isPhoto: isPhoto,
            Mult: Mult,
            IsAdd: IsAdd,
            IncNum: IncNum,
            IsFollow: IsFollow,
            Title: Title,
            Commis: Commis,
            IsShow: IsShow,
            Metro: Metro,
            betNumber: betNs,
            betRecords: berRs,
            betAmount: (berRs.length * app.PRICE * Mult * (IncNum == '' ? 1 : IncNum)) * (IsAdd == 0 ? 1 : 1.5)
        }
        if (postBetData.betRecords.length * Number(Mult) > app.DLTMaxBetAmount) {
            this.do_toast('单笔金额不能超过2万元', 500);
            return;
        }        
        this._clear_bet();
        this.props.navigation.navigate('BetOrder', {
            type: 1,
            postBetData: postBetData,
            game_model: "DLTGame",
        })
    }
    do_bet_follow = () => {
        let { computeState, name, isPhoto, Mult, IsAdd, IncNum, IsFollow, Title, Commis, IsShow, Metro, BetNumber } = this.state;
        if (computeState == false) {
            return;
        }
        if (BetNumber.length == 0) {
            this.do_toast('请至少选择一注', 1000);
            return;
        }
        if (IncNum > 1) {
            this.do_toast('追期不能发起跟单', 1000);
            return;
        }
        let betNs = [];
        let berRs = [];
        for (let i = 0; i < BetNumber.length; i++) {
            let betN = BetNumber[i].BetNumber;
            let berR = BetNumber[i].betRecords;
            let NoID = ((i + 1) * 10) + betN.Type;
            betN.NoID = NoID;
            for (let j = 0; j < berR.length; j++) {
                berR[j].NoID = NoID;
                berR[j].multNum = Mult;
                berRs.push(berR[j]);
            }
            betNs.push(betN);
        }
        let postBetData = {
            name: name,
            isPhoto: isPhoto,
            Mult: Mult,
            IsAdd: IsAdd,
            IncNum: IncNum,
            IsFollow: IsFollow,
            Title: Title,
            Commis: Commis,
            IsShow: IsShow,
            Metro: Metro,
            betNumber: betNs,
            betRecords: berRs,
            betAmount: (berRs.length * app.PRICE * Mult * (IncNum == '' ? 1 : IncNum)) * (IsAdd == 0 ? 1 : 1.5)
        }
        if (postBetData.betRecords.length * Number(Mult) > app.DLTMaxBetAmount) {
            this.do_toast('单笔金额不能超过2万元', 500);
            return;
        }
        this.props.navigation.navigate('Follow', {
            game_model: "DLTGame",
            postBetData: postBetData,
            name: name,
            beishuInput: Mult,
        })
    }
    del_show_bet = (index) => {
        this.setState({
            betNumber: Ugame.delDLTSelectList(index)
        }, () => {
            this.computeBetNumber();
        });
    }
    renderListsitem = ({ item, index }) => {
        let betNumber = item.BetNumber.BetNumber.split('|');
        let red_ball = betNumber[0].split(',');
        let blue_ball = betNumber[1].split(',');
        let type = item.BetNumber.Type;
        let tips = '';
        switch (type) {
            case BETTYPE.One:
                tips = '单注';
                break;
            case BETTYPE.Multiple:
                tips = '复式';
                break;
            case BETTYPE.Bladder:
                tips = '胆拖';
                break;
        }
        let betCount = item.betCount;
        let betAmount = item.betAmount;
        var ball_node = [];
        for (let i = 0; i < red_ball.length; i++) {
            let css = { color: '#d0162e', paddingRight: 5 };
            ball_node.push(
                <Text key={ball_node.length} style={css}>{red_ball[i]}</Text>
            );
        }
        for (let i = 0; i < blue_ball.length; i++) {
            let css = { color: '#1094d8', paddingRight: 5 };
            ball_node.push(
                <Text key={ball_node.length} style={css}>{blue_ball[i]}</Text>
            );
        }
        return (
            <View style={Styles.DLTbox_lists}>
                <TouchableOpacity onPress={() => { this.del_show_bet(index) }}>
                    <View style={Styles.DLTbox_lists_item}>
                        <Image resizeMode="cover" source={require('../../../image/js_img_ic_order_delete.png')} />
                    </View>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => { this.on_show_bet(index) }}>
                    <View style={Styles.DLTbox_lists_item2}>
                        <View style={{ flexDirection: 'row', justifyContent: 'flex-start', flexWrap: 'wrap' }}>
                            {ball_node}
                        </View>
                        <Text style={{ color: '#999999' }}>{tips}{betCount}注{betAmount}元</Text>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => { this.on_show_bet(index) }}>
                    <View style={Styles.DLTbox_lists_item}>
                        <Image resizeMode="cover" style={Styles.jt} source={require('../../../image/js_img_list_jump.png')} />
                    </View>
                </TouchableOpacity>
            </View>
        );
    }

    do_toast = (str, time) => {
        this.setState({
            message: str,
            toastModelVisible: true
        });
        this._time = setTimeout(() => {
            this.setState({
                message: '',
                toastModelVisible: false
            });
            clearTimeout(this._time);
        }, time);
    }
    toast = () => {
        return (
            <Modal
                animationType="fade"
                transparent={true}
                visible={this.state.toastModelVisible}
                onRequestClose={() => {
                    this.setState({
                        toastModelVisible: false
                    });
                }}
            >
                <View style={{ flexDirection: 'row', justifyContent: 'center', position: 'absolute', bottom: 100, width: width }}>
                    <Text style={{ backgroundColor: 'rgba(0,0,0,0.5)', color: '#ffffff', borderRadius: 10, height: 40, lineHeight: 40, paddingLeft: 20, paddingRight: 20 }}>{this.state.message}</Text>
                </View>
            </Modal>
        );
    }
    on_random_one_balls() {
        let { BetNumber } = this.state;
        //随机红球
        let red_ball = [];
        while (red_ball.length < 5) {
            let n = Utils.random_int(1, 35);
            let bool = true;
            for (let i = 0; i < red_ball.length; i++) {
                if (n == red_ball[i]) {
                    bool = false;
                    break;
                }
            }
            if (bool) {
                red_ball.push(Utils.pad(n));
            }
        }
        red_ball = red_ball.sort(function (a, b) { return a - b });
        //随机篮球
        let blue_ball = [];
        while (blue_ball.length < 2) {
            let n = Utils.random_int(1, 35);
            let bool = true;
            for (let i = 0; i < blue_ball.length; i++) {
                if (n == blue_ball[i]) {
                    bool = false;
                    break;
                }
            }
            if (bool) {
                blue_ball.push(Utils.pad(n));
            }
        }
        blue_ball = blue_ball.sort(function (a, b) { return a - b });

        let obj = DLTBall.betNumberComb(BETTYPE.One, this.state.Number, [], red_ball, [], blue_ball, 1);
        this.setState({
            BetNumber: Ugame.addDLTSelectList([obj])
        }, () => {
            this.computeBetNumber();
        });
    }
    //减少追多少期
    _on_reduce_IncNum() {
        let { IncNum } = this.state;
        if (IncNum == '' || Number(IncNum) <= 1) {
            return;
        }
        IncNum = Number(IncNum) - 1;
        this.setState({
            IncNum: IncNum.toString(),
        }, () => {
            this.computeBetNumber();
        });
    }
    //增加追多少期
    _on_increase_IncNum() {
        let { IncNum } = this.state;
        if (IncNum == '' || Number(IncNum) <= 1) {
            IncNum = 1;
        }
        IncNum = Number(IncNum) + 1;
        this.setState({
            IncNum: IncNum.toString(),
        }, () => {
            this.computeBetNumber();
        });
    }
    //修改追多少期
    _onIncNumChangeText(count) {
        count = Utils.checkbeishuInput(count);
        this.setState({
            IncNum: count.toString(),
        }, () => {
            this.computeBetNumber();
        });
    }
    //减少倍数
    _on_reduce_Mult() {
        let { Mult } = this.state;
        if (Mult == '' || Number(Mult) <= 1) {
            return;
        }
        Mult = Number(Mult) - 1;
        this.setState({
            Mult: Mult.toString(),
        }, () => {
            this.computeBetNumber();
        });
    }
    //增加倍数
    _on_increase_Mult() {
        let { Mult } = this.state;
        if (Mult == '' || Number(Mult) <= 1) {
            Mult = 1;
        }
        Mult = Number(Mult) + 1;
        this.setState({
            Mult: Mult.toString(),
        }, () => {
            this.computeBetNumber();
        });
    }
    //修改倍数
    _onMultChangeText(count) {
        count = Utils.checkbeishuInput(count);
        this.setState({
            Mult: count.toString(),
        }, () => {
            this.computeBetNumber();
        });
    }
    _on_change_is_need_pictures() {
        this.setState({
            isPhoto: this.state.isPhoto === 0 ? 1 : 0
        });
    }
    _do_IsAdd_opt() {
        this.setState({
            IsAdd: this.state.IsAdd === 0 ? 1 : 0
        }, () => {
            this.computeBetNumber();
        });
    }
    render() {
        let { BetNumber, Mult, isPhoto, IncNum, IsAdd, bet_count, bet_amount, isGold, computeState } = this.state;
        return (
            <View style={Styles.container}>
                <StatusBar translucent={true} backgroundColor="transparent" />
                <View style={Styles.header}>
                    <TouchableOpacity onPress={() => { this._add_bet() }}>
                        <View style={Styles.header_item}>
                            <Text style={{ color: '#666666', fontSize: 12 }}>自选号码</Text>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => { this.on_random_one_balls() }}>
                        <View style={Styles.header_item}>
                            <Text style={{ color: '#666666', fontSize: 12 }}>机选一注</Text>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => { this._clear_bet() }}>
                        <View style={Styles.header_item}>
                            <Text style={{ color: '#666666', fontSize: 12 }}>清空重选</Text>
                        </View>
                    </TouchableOpacity>
                </View>
                <ScrollView style={{ height: 400 }}>
                    <FlatList
                        data={BetNumber}
                        extraData={this.state}
                        keyExtractor={(item, index) => index.toString()}
                        renderItem={this.renderListsitem}
                    />
                    <TouchableOpacity onPress={() => this._on_change_is_need_pictures()}>
                        <View style={Styles.tips_info}>
                            {isPhoto === 1 ? <Image resizeMode="cover" source={require('../../../image/js_img_ic_login_checkbox_checked.png')} /> : <Image resizeMode="cover" source={require('../../../image/js_img_ic_login_checkbox.png')} />}
                            <Text style={{ fontSize: 12, marginLeft: 5 }}>要求店主上传照片</Text>
                        </View>
                    </TouchableOpacity>
                </ScrollView>
                <View style={Styles.yujijinge}>
                    <View style={Styles.yujijinge_sum}>
                        <Text style={{ fontSize: 12 }}>{bet_count}</Text>
                        <Text style={{ fontSize: 12 }}>注</Text>
                        <Text style={{ fontSize: 12, color: '#d0162e' }}>{bet_amount}</Text>
                        <Text style={{ fontSize: 12 }}>元</Text>
                    </View>
                </View>
                <View style={Styles.bet_type}>
                    <View style={Styles.beishu}>
                        <Text style={{ fontSize: 14, color: '#434343' }}>追</Text>
                        <View style={Styles.beishu_input}>
                            <TouchableOpacity onPress={() => this._on_reduce_IncNum()}>
                                <View style={{ padding: 5 }}>
                                    <Image resizeMode="cover" source={require('../../../image/js_img_icon_subtract.png')} />
                                </View>
                            </TouchableOpacity>
                            <TextInput
                                style={{ height: 25, padding: 0, lineHeight: 25, textAlign: 'center', width: 45, borderLeftWidth: 1, borderRightWidth: 1, borderColor: '#cacaca' }}
                                value={'' + IncNum}
                                keyboardType='numeric'
                                placeholder={'1'}
                                onChangeText={(IncNum) => this._onIncNumChangeText(IncNum)}
                            />
                            <TouchableOpacity onPress={() => this._on_increase_IncNum()}>
                                <View style={{ padding: 5 }}>
                                    <Image resizeMode="cover" source={require('../../../image/js_img_sub_icon_add.png')} />
                                </View>
                            </TouchableOpacity>
                        </View>
                        <Text style={{ fontSize: 14, color: '#434343' }}>期</Text>
                    </View >
                    <View style={Styles.beishu}>
                        <Text style={{ fontSize: 14, color: '#434343' }}>投</Text>
                        <View style={Styles.beishu_input}>
                            <TouchableOpacity onPress={() => this._on_reduce_Mult()}>
                                <View style={{ padding: 5 }}>
                                    <Image resizeMode="cover" source={require('../../../image/js_img_icon_subtract.png')} />
                                </View>
                            </TouchableOpacity>
                            <TextInput
                                style={{ height: 25, padding: 0, lineHeight: 25, textAlign: 'center', width: 45, borderLeftWidth: 0.5, borderRightWidth: 0.5, borderColor: '#cacaca' }}
                                value={'' + Mult}
                                keyboardType='numeric'
                                placeholder={"1"}
                                onChangeText={(Mult) => this._onMultChangeText(Mult)}
                            />
                            <TouchableOpacity onPress={() => this._on_increase_Mult()}>
                                <View style={{ padding: 5 }}>
                                    <Image resizeMode="cover" source={require('../../../image/js_img_sub_icon_add.png')} />
                                </View>
                            </TouchableOpacity>
                        </View>
                        <Text style={{ fontSize: 14, color: '#434343' }}>倍</Text>
                    </View >
                    <TouchableOpacity onPress={() => this._do_IsAdd_opt()}>
                        <View style={{
                            width: 75, flexDirection: 'row',
                            justifyContent: 'center',
                            alignItems: 'center'
                        }}>
                            {IsAdd === 0 ?
                                <Image resizeMode="cover" source={require('../../../image/js_img_ic_login_checkbox.png')} />
                                :
                                <Image resizeMode="cover" source={require('../../../image/js_img_ic_login_checkbox_checked.png')} />
                            }
                            <Text style={{ fontSize: 14, color: '#434343' }}> 追加</Text>
                        </View>
                    </TouchableOpacity>
                </View>

                <View style={Styles.bottom}>
                    {isGold == 1 ?
                        <TouchableOpacity onPress={() => this.do_bet_follow()}>
                            <View style={{
                                flexDirection: 'row',
                                justifyContent: 'center',
                                alignItems: 'center', width: width / 2
                            }}>
                                <Image resizeMode="cover" source={require('../../../image/js_img_icon_edit_hm.png')} />
                                <Text style={{ color: '#d0162e', marginLeft: 5 }}>发起跟单</Text>
                            </View>
                        </TouchableOpacity> :
                        null
                    }

                    {computeState == true ?
                        <TouchableOpacity onPress={() => this.do_bet_order()}>
                            <View style={[Styles.tuzhu, isGold == 1 ? { width: width / 2 } : { width: width }]}>
                                <Text style={{ color: '#ffffff' }}>确认投注</Text>
                            </View>
                        </TouchableOpacity> :
                        <View style={[Styles.tuzhu_hui, isGold == 1 ? { width: width / 2 } : { width: width }]}>
                            <Text style={{ color: '#ffffff' }}>确认投注</Text>
                        </View>
                    }
                </View>
                {this.toast()}
            </View>
        )
    }



}
